<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>博客创作</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">
  <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    html, 
    body {
      background-color: #fff;
      height: 100%;
      overflow: hidden;
      color: #333;
    }

    #top-container {
      border-bottom: 1px solid #e8e8e8;
      padding-left: 30px;
    }

    #editor-toolbar {
      width: 1350px;
      background-color: #FCFCFC;
      margin: 0 auto;
    }

    #content {
      height: calc(100% - 40px);
      background-color: rgb(245, 245, 245);
      overflow-y: auto;
      position: relative;
    }

    #editor-container {
      width: 850px;
      margin: 30px auto 150px auto;
      background-color: #fff;
      padding: 20px 50px 50px 50px;
      border: 1px solid #e8e8e8;
      box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
    }

    #title-container {
      padding: 20px 0;
      border-bottom: 1px solid #e8e8e8;
    }

    #title-container input {
      font-size: 30px;
      border: 0;
      outline: none;
      width: 100%;
      line-height: 1;
    }

    #editor-text-area {
      min-height: 900px;
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <div id="top-container">
    <p>
      <a href="./blog.html">&lt;&lt; 返回 博客管理</a>
    </p>
  </div>
  <div style="border-bottom: 1px solid #e8e8e8;">
    <div id="editor-toolbar"></div>
    <div id="editor-actions" style="background-color: #FCFCFC; padding: 10px 0; border-top: 1px solid #e8e8e8;">
      <div style="width: 1350px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center;">
        <div>
          <button id="save-draft-btn" style="padding: 8px 16px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px;">
            <i class="fas fa-save"></i> 保存草稿
          </button>
          <button id="publish-btn" style="padding: 8px 16px; background: #52c41a; color: white; border: none; border-radius: 4px; cursor: pointer;">
            <i class="fas fa-paper-plane"></i> 发布文章
          </button>
        </div>
        <div style="display: flex; align-items: center; gap: 10px;">
          <label style="font-size: 14px; color: #666;">
            <input type="checkbox" id="auto-save-toggle" checked> 自动保存
          </label>
          <span id="auto-save-status" style="font-size: 12px; color: #999;">已开启</span>
          <span id="last-save-time" style="font-size: 12px; color: #999;">未保存</span>
        </div>
      </div>
    </div>
  </div>
  <div id="content">
    <div id="editor-container">
      <div id="title-container">
        <input placeholder="Page title...">
      </div>
      <div id="editor-text-area"></div>
    </div>
  </div>

  <!-- <script src="https://cdn.jsdelivr.net/npm/@wangeditor/editor@latest/dist/index.min.js"></script> -->
  <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
  <script src="../scripts/api-client.js"></script>
  <script>
    const E = window.wangEditor

    // 切换语言
    const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
    E.i18nChangeLanguage(LANG)

    // 编辑器状态管理
    let autoSaveTimer = null;
    let isAutoSaveEnabled = true;
    let lastSaveTime = null;
    let hasUnsavedChanges = false;

    const editorConfig = {
      placeholder: 'Type here...',
      scroll: false, // 禁止编辑器滚动
      MENU_CONF: {
        uploadImage: {
          fieldName: 'your-fileName',
          base64LimitSize: 10 * 1024 * 1024 // 10M 以下插入 base64
        }
      },
      onChange(editor) {
        console.log(editor.getHtml())
        hasUnsavedChanges = true;
        updateSaveStatus();
        
        // 自动保存逻辑
        if (isAutoSaveEnabled) {
          clearTimeout(autoSaveTimer);
          autoSaveTimer = setTimeout(() => {
            saveDraft();
          }, 3000); // 3秒后自动保存
        }
      }
    }

    // 先创建 editor
    const editor = E.createEditor({
      selector: '#editor-text-area',
      content: [],
      // html: '',
      config: editorConfig
    })

    // 创建 toolbar
    const toolbar = E.createToolbar({
      editor,
      selector: '#editor-toolbar',
      config: {
        excludeKeys: 'fullScreen',
      }
    })

    // 点击空白处 focus 编辑器
    document.getElementById('editor-text-area').addEventListener('click', e => {
      if (e.target.id === 'editor-text-area') {
        editor.blur()
        editor.focus(true) // focus 到末尾
      }
    })

    // 保存草稿功能
    async function saveDraft() {
      const title = document.querySelector('#title-container input').value.trim();
      const content = editor.getHtml();
      
      if (!title && !content) {
        return; // 空内容不保存
      }
      
      try {
        const draftData = {
          title: title || '无标题草稿',
          content: content,
          status: 'draft',
          lastModified: new Date().toISOString()
        };
        
        // 保存到本地存储
        localStorage.setItem('currentDraft', JSON.stringify(draftData));
        
        // 同时保存到服务器（如果已登录）
        try {
          const response = await apiClient.post('/api/articles', {
            title: draftData.title,
            content: draftData.content,
            status: 'draft'
          });
          
          if (response.success) {
            console.log('草稿已同步到服务器');
          }
        } catch (serverError) {
          console.warn('服务器保存失败，但本地草稿已保存:', serverError);
        }
        
        // 更新保存状态
        lastSaveTime = new Date();
        hasUnsavedChanges = false;
        updateSaveStatus();
        
        console.log('草稿已保存');
      } catch (error) {
        console.error('保存草稿失败:', error);
      }
    }

    // 发布文章功能
    async function publishArticle() {
      const title = document.querySelector('#title-container input').value.trim();
      const content = editor.getHtml();
      
      if (!title) {
        alert('请输入文章标题');
        return;
      }
      
      if (!content) {
        alert('请输入文章内容');
        return;
      }
      
      try {
        const articleData = {
          title: title,
          content: content,
          status: 'published',
          publishedAt: new Date().toISOString()
        };
        
        // 实际项目中应该调用API发布文章
        console.log('发布文章:', articleData);
        
        // 清除草稿
        localStorage.removeItem('currentDraft');
        
        alert('文章发布成功！');
        window.location.href = './blog.html';
      } catch (error) {
        console.error('发布文章失败:', error);
        alert('发布失败，请重试');
      }
    }

    // 更新保存状态显示
    function updateSaveStatus() {
      const statusElement = document.getElementById('auto-save-status');
      const timeElement = document.getElementById('last-save-time');
      
      if (isAutoSaveEnabled) {
        statusElement.textContent = hasUnsavedChanges ? '保存中...' : '已保存';
        statusElement.style.color = hasUnsavedChanges ? '#faad14' : '#52c41a';
      } else {
        statusElement.textContent = '已关闭';
        statusElement.style.color = '#999';
      }
      
      if (lastSaveTime) {
        timeElement.textContent = `最后保存: ${lastSaveTime.toLocaleTimeString()}`;
      } else {
        timeElement.textContent = '未保存';
      }
    }

    // 加载草稿
    function loadDraft() {
      try {
        const savedDraft = localStorage.getItem('currentDraft');
        if (savedDraft) {
          const draft = JSON.parse(savedDraft);
          document.querySelector('#title-container input').value = draft.title;
          editor.setHtml(draft.content);
          
          if (draft.lastModified) {
            lastSaveTime = new Date(draft.lastModified);
            updateSaveStatus();
          }
          
          console.log('草稿已加载');
        }
      } catch (error) {
        console.error('加载草稿失败:', error);
      }
    }

    // 初始化事件监听
    function initEventListeners() {
      // 保存草稿按钮
      document.getElementById('save-draft-btn').addEventListener('click', saveDraft);
      
      // 发布文章按钮
      document.getElementById('publish-btn').addEventListener('click', publishArticle);
      
      // 自动保存开关
      document.getElementById('auto-save-toggle').addEventListener('change', function(e) {
        isAutoSaveEnabled = e.target.checked;
        updateSaveStatus();
        
        if (isAutoSaveEnabled && hasUnsavedChanges) {
          // 如果重新开启自动保存且有未保存的更改，立即保存
          saveDraft();
        }
      });
      
      // 页面关闭前提示保存
      window.addEventListener('beforeunload', function(e) {
        if (hasUnsavedChanges) {
          e.preventDefault();
          e.returnValue = '';
          return '';
        }
      });
      
      // 标题输入框变化也触发保存状态更新
      document.querySelector('#title-container input').addEventListener('input', function() {
        hasUnsavedChanges = true;
        updateSaveStatus();
        
        if (isAutoSaveEnabled) {
          clearTimeout(autoSaveTimer);
          autoSaveTimer = setTimeout(() => {
            saveDraft();
          }, 3000);
        }
      });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      initEventListeners();
      loadDraft();
      updateSaveStatus();
    });
  </script>
</body>

</html>